package com.zbxx.service.impl;

import com.zbxx.dao.SeckillDao;
import com.zbxx.dao.SuccessKillDao;
import com.zbxx.domain.Seckill;
import com.zbxx.domain.Successkilled;
import com.zbxx.dto.Exposer;
import com.zbxx.dto.SeckillExecution;
import com.zbxx.enums.SeckillStatEnum;
import com.zbxx.exception.SeckillException;
import com.zbxx.exception.SeckillCloseException;
import com.zbxx.exception.RepeatKillException;
import com.zbxx.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class SeckillServiceimpl implements SeckillService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private SeckillDao seckillDao;
    @Resource
    private SuccessKillDao successKillDao;

    //md5盐值字符串，用来混淆md5
    private final String slat = "adazc6564378ad7ojfiq";

    @Override
    public List<Seckill> getSeckilllist() {
        return seckillDao.queryAll(0, 8);
    }

    @Override
    public Seckill getByid(long id) {
        return seckillDao.queryByid(id);
    }

    @Override
    public Exposer exportSeckillUrl(long id) {

        Seckill seckill = seckillDao.queryByid(id);
        System.out.println("cccccccccccccc"+seckill.getStartTime());
        if (seckill == null) {
            return new Exposer(false, id);
        }
        Date startTime = seckill.getStartTime();
        Date endTime = seckill.getEndTime();
        //系统时间
        Date nowTime = new Date();
        //根据毫秒计算，如果小于开始时间咋没开始，大于结束时间则已结束
        if (nowTime.getTime() < startTime.getTime()
                || nowTime.getTime() > endTime.getTime()) {
            return new Exposer(false, nowTime.getTime(), startTime.getTime(), endTime.getTime(), id);
        }
        //转化特定字符串的过程，不可逆
        String md5 = getMD5(id);
        return new Exposer(true, md5, id);
    }

    private String getMD5(long id) {
        String base = id + "/" + slat;
        String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
        return md5;
    }

    @Override
    @Transactional
    /*
    标注为事务方法
     *使用注解控制事务的优点
     * 1.明确标注事务的编程风格
     * 2.保证事务方法的执行时间尽可能短，不要穿插其他的网络操作，rpc/http请求或者剥离的事务方法的外面
     * 3.不是所有的方法都要事务，比如只有一条 修改操作，只读操作不需要事务控制
     * */
    public SeckillExecution executeSeckill(long id, long userPhone, String md5)
            throws SeckillException, SeckillCloseException, RepeatKillException {
        if (md5 == null || !md5.equals(getMD5(id))) {
            throw new SeckillException("seckill data rewrite");
        }
        //执行秒杀逻辑:减库存+记录秒杀行为
        Date nowTime = new Date();
        try {
            //减库存
            int updateCount = seckillDao.reduceNumber(id, nowTime);
            if (updateCount <= 0) {
                //没有更新到记录,秒杀结束
                throw new SeckillCloseException("seckill is closed");
            } else {
                //减库存成功以后记录购买行为
                int insertCount = successKillDao.insertSuccessKilled(id, userPhone);
                //唯一:id,userPhone
                if (insertCount <= 0) {
                    //重复秒杀
                    throw new RepeatKillException("seckill repeated");
                } else {
                    //秒杀成功了
                    Successkilled successkilled = successKillDao.queryByidWithSeckill(id);
                    return new SeckillExecution(id,SeckillStatEnum.SUCCESS, successkilled);//枚举表示成功
                }
            }
        } catch (SeckillCloseException e1) {
            throw e1;
        } catch (SeckillException e2) {
            throw e2;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            //所有编译器异常转换成运行期异常
            throw new SeckillException("seckill inner error" + e.getMessage());
        }

    }

}
